﻿using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System;

namespace Toybox.NicoSharp.Live
{
	using Extensions;
	using Utilities;
	using Logger;

	public class LiveTag
	{

		#region [Static]

		/// <summary>
		/// 放送タグ取得用Rgex
		/// </summary>
		public const string REGEX_LIVETAGS = "<a.+?>(?<tag>.+?)</a><.+?\">\\((?<count>.*?)\\)</span>";

		/// <summary>
		/// タグ書き換え回数取得用Regex
		/// </summary>
		public const string REGEX_TAGREV = "{'rev':(?<rev>.*?)}";

		/// <summary>
		/// タグ取得
		/// </summary>
		/// <param name="completeId"></param>
		/// <param name="cookies"></param>
		/// <returns></returns>
		public static LiveTag[] GetTags(string completeId, CookieCollection cookies = null)
		{
			Dictionary<string, string> dict = new Dictionary<string, string>();
			dict.Add("v", completeId);
			dict.Add("version", "zero");

			string url = NicoUrls.LiveApi + "livetags.php?" + Serializer.AndEqualPairSerializer(dict);
			string html = NicoWebClient.Get(url, cookies.Coerce());

			List<LiveTag> result = new List<LiveTag>();

			MatchCollection matches = Regex.Matches(html, REGEX_LIVETAGS);
			foreach (Match match in matches)
			{
				LiveTag tag = new LiveTag()
				{
					tag = match.Groups["tag"].Value,
					count = int.Parse(match.Groups["count"].Value),
				};
				result.Add(tag);
			}

			return result.ToArray();
		}

		/// <summary>
		/// タグ書き換え回数取得
		/// </summary>
		/// <param name="completeId"></param>
		/// <param name="cookies"></param>
		/// <returns></returns>
		public static int GetTagRev(string completeId, CookieCollection cookies = null)
		{
			try
			{
				string url = NicoUrls.LiveApi + "tagrev/" + completeId;
				string html = NicoWebClient.Get(url, cookies.Coerce());

				Match match = Regex.Match(html, REGEX_TAGREV);
				return match.Success ? int.Parse(match.Groups["rev"].Value) : -1;
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
				return -1;
			}
		}

		#endregion [Static]


		#region Public Members

		public string tag;

		public int count;

		#endregion Public Members

	}
}
